package com.lujieni.springbootnacos.client.config;

import com.lujieni.springbootnacos.client.util.EnvUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {

    /**
     * spring.cloud.nacos.discovery.metadata.tag是Spring Cloud Alibaba Nacos Discovery 组件中的一个配置项，
     * 用于在服务注册到Nacos时,给服务实例添加元数据标签 (metadata tags)
     */
    private static final String NACOS_META_PREFIX = "spring.cloud.nacos.discovery.metadata.";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String,Object> map = new HashMap<>();
        map.put("name", "qiqi");
        map.put("age", "31");
        // 动态添加或修改环境属性
        environment.getPropertySources().addLast(
            new MapPropertySource("custom", map)
        );

        // 从配置文件中读取tag
        String tag = EnvUtils.getTag(environment);
        environment.getSystemProperties().put(NACOS_META_PREFIX + "tag", tag);

        try {
            ClassPathResource resource = new ClassPathResource("META-INF/build-info.properties");
            Properties props = PropertiesLoaderUtils.loadProperties(resource);
            String buildTime = props.getProperty("build.time");
            // 1. 将 ISO 8601 字符串解析为 Instant 对象
            Instant instant = Instant.parse(buildTime);
            // 2. 将 Instant 对象转换为 LocalDateTime 对象 (指定时区)
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai")); // 使用上海时区，可以根据需要更改
            // 3. 使用 DateTimeFormatter 格式化 LocalDateTime 对象
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedTime = localDateTime.format(formatter);
            environment.getSystemProperties().put(NACOS_META_PREFIX + "build.time", formattedTime);
        } catch (IOException e) {
            // 忽略文件不存在的情况
        }


    }
}